package com.mondo.financialwallet.presentation.ui.window;

import android.content.Context;
import android.support.v7.widget.ListPopupWindow;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.mondo.financialwallet.R;

import java.util.List;

public class AreaSelectionPopupWindow {

    private ListPopupWindow mPopupWindow;
    private OnClickListener onClickListener;

    public AreaSelectionPopupWindow(Context context, List<Area> list){
        mPopupWindow = new ListPopupWindow(context);
        mPopupWindow.setAdapter(new AresSelectionArrayAdapter(list));
        mPopupWindow.setHeight(context.getResources().getDimensionPixelOffset(R.dimen.area_selection_window_height));
    }

    public void show(View anchor) {
        mPopupWindow.setAnchorView(anchor);
        mPopupWindow.show();
    }

    public void setOnClickListener(OnClickListener onClickListener){
        this.onClickListener = onClickListener;
    }

    class AresSelectionArrayAdapter extends BaseAdapter{

        private final List<Area> list;

        AresSelectionArrayAdapter(List<Area> list){
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Area area = list.get(position);
            View rootView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_area_selection_list, null);
            TextView countryTextView = rootView.findViewById(R.id.country_text_view);
            TextView areaTextView = rootView.findViewById(R.id.area_text_view);
            countryTextView.setText(area.area);
            areaTextView.setText(area.number);
            rootView.setOnClickListener(v -> {
                if (onClickListener != null){
                    onClickListener.onClick(area.number);
                }

                if (mPopupWindow.isShowing()){
                    mPopupWindow.dismiss();
                }

            });
            return rootView;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }
    }


    public static class Area {
        private String area;

        private String number;

        public Area(String area, String number) {
            this.area = area;
            this.number = number;
        }
    }

    public interface OnClickListener {
        void onClick(String text);
    }
}
